package lumis.portal.el;

import java.lang.reflect.Method;

import lumis.portal.PortalException;
import lumis.portal.PortalStringResource;
import lumis.portal.manager.ManagerFactory;
import lumis.util.IResource;
import lumis.util.log.ILogger;
import lumis.util.log.LoggerFactory;

/**
 * Portal general EL function mapper.
 * <p>
 * Resolves EL functions to be available in any portal context. 
 *
 * @version $Revision: 11804 $ $Date: 2010-07-29 10:06:21 -0300 (Thu, 29 Jul 2010) $
 * @since 5.6.0
 */	
public class PortalFunctionMapper implements IExtendedFunctionMapper
{	
	private static ILogger logger = LoggerFactory.getLogger(PortalFunctionMapper.class);
	
	/**
	 * Resolves the string. 
	 * @param args  the localize function parameters. First argument is the
	 * identifier of the string to be localized. The second argument is optional,
	 * and is the resource path to be included in the localization.
	 * @return		localized string.
	 * @throws PortalException	if an error occur localizing the string.
	 * @since 5.6.0
	 */
	public static String localize(String[] args) throws PortalException
	{
		if (args == null || args.length == 0)
			throw new IllegalArgumentException("args cannot be null or empty");
		
		IResource resource = new PortalStringResource();
		if (args.length > 1)
			resource.addResourcePath(args[1]);
		return ManagerFactory.getLocalizationManager().localize(args[0], resource);
	}
	
	public Method resolveFunction(String prefix, String methodName)
	{
		try
		{
			if (methodName.equals("localize"))
			{
				return PortalFunctionMapper.class.getMethod("localize", new Class[]{String[].class});	
			}
			else
			{
				logger.error("Could not resolve function \"" + methodName + "\"");
				return null;
			}	
		}
		catch(NoSuchMethodException e)		
		{
			logger.error("Could not resolve function \"" + methodName + "\"", e);
			return null;
		}
	}	
}